<template>
	<view class="w100" :style="{ minHeight: height + 'rpx' }">
		<view class="w100 justify-between gap20">
			<view class="flex-1 u-line-1 mr20" :style="{
          textAlign: align,
          lineHeight: height + 'rpx',
          fontSize: fontSize,
        }" @click="open = true">
				<span v-if="showValue">{{ showValue }}</span>
				<span class="holder" v-else>{{ placeholder }}</span>
			</view>
			<view class="centerV pb2">
				<u-icon :name="closeable ? (showValue ? 'close' : icon) : icon" :size="iconSize + 'rpx'"
					@click="onIcon"></u-icon>
			</view>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<root-portal>
		<!-- #endif -->
			<u-picker :show="open" :columns="dateOptions" :keyName="keyLabel" @cancel="open = false"
				@confirm="onConfirm"></u-picker>
		<!-- #ifdef MP-WEIXIN -->
		</root-portal>
		<!-- #endif -->
	</view>
</template>

<script setup>
	import {
		ref,
		watchEffect
	} from "vue";
	import {
		onLoad
	} from "@dcloudio/uni-app";

	const props = defineProps({
		modelValue: {
			type: [String, Number],
			default: null,
		},
		height: {
			type: Number,
			default: 60,
		},
		options: {
			required: true,
			type: [Array, Object],
			default: [],
		},
		fontSize: {
			type: String,
			default: '28rpx',
		},
		keyLabel: {
			type: String,
			default: "label",
		},
		keyValue: {
			type: String,
			default: "value",
		},
		align: {
			type: String,
			default: "right",
		},
		placeholder: {
			type: String,
			default: "请选择",
		},
		icon: {
			type: String,
			default: "arrow-down",
		},
		iconSize: {
			type: Number,
			default: 28,
		},
		closeable: {
			type: Boolean,
			default: true,
		},
	});
	const emit = defineEmits(["update:modelValue", "confirm"]);

	// 当前选中数据
	const showValue = ref();
	const current = ref(null);
	const dateOptions = ref([]);

	watchEffect(() => {
		if (!props.options.length) return false
		current.value = props.options.find((item) => item.value === props.modelValue);
		if (current.value) {
			showValue.value = current.value.label;
		} else {
			showValue.value = null;
			showValue.value = props.modelValue;
		}
		dateOptions.value[0] = props.options;

	});

	// 控制选项框
	const open = ref(false);

	// 确认选项数据
	function onConfirm(e) {
		const choosed = e.value[0];
		current.value = e.value;
		showValue.value = choosed[props.keyLabel];
		open.value = false;
		emit("update:modelValue", choosed[props.keyValue]);
		emit("confirm", choosed[props.keyValue]);
	}

	function onIcon() {
		if (props.closeable) {
			if (showValue.value) {
				showValue.value = null;
				current.value = null;
				emit("update:modelValue", null);
				emit("confirm", null);
			} else {
				open.value = !open.value;
			}
		} else {
			open.value = !open.value;
		}
	}
	// #ifdef MP-WEIXIN
	defineOptions({
		options: {
			styleIsolation: "shared",
		},
	});
	// #endif
</script>

<style scoped lang="scss">
	.holder {
		color: rgb(192, 196, 204);
	}

	:deep() {
		.u-popup__content {
			border-radius: 20rpx 20rpx 0 0;
		}
	}
</style>